package com.example.dell.newstart.cart;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.example.dell.newstart.MainActivity;
import com.example.dell.newstart.bean.MyApp;

import com.example.dell.newstart.R;
import com.example.dell.newstart.base.BaseFragment;

import com.example.dell.newstart.bean.Order;
import com.example.dell.newstart.pay.AuthResult;
import com.example.dell.newstart.pay.PayResult;
import com.example.dell.newstart.pay.util.OrderInfoUtil2_0;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * created by Dongkai on 2018/12/4
 */

public class CartFragment extends BaseFragment implements CartAdapter.OnPriceChangeListener, CartAdapter.OnCartVisibilityChangeListener {

    private static final String TAG = "CartActivity";

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016092000551580";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA_PRIVATE = "";
    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVRDz2CN0SwP29sUu4Y13wCTCa5vc0S+5Pqr40Ld72UwLgYJjC6Hy+yYLCahOSSKPfljR8GF92p0K5aOeigWdvgvPbFdZ/Oc5QoQprGieyZKCVsIO5Xakzbh1D0Clpo68etQ4Sya071l+jsD0jY5tK1Srf3UkQc2HIezCRPGHB/IPW68LoT/bNrSELnZt89c3A0nMpT3I4x05tME9rnrUjmFdBh3rVXxBK4vTZ6QvOgDzKjuRKiyG80caKi/LTBgZy7Q4j2F04hNu8uaL/R0DGjFNNyvROP4zBuNDEddkUGl/4O0puPiXF+MsHAX7Cvg1S+aZkgB50+6bzAyxGZ9zdAgMBAAECggEBAJTwUAafUA1N3KdCj5gZRTxinqA/lvrd4HOg0a7NLj4m4QZkT6snBB+VyY0O2dY6hr+aPdNAjkLmMtIbslEqQFt/P+CMUr2NWEm0/fqoTHrojcGcgZHOGGGDkEqQsKtHFgDC/y4dzK7SWv6NEVWKtaRAVO38s48alXqWleeIHNmEwlS8urKJqSALtL1Q+NF6jTRdle7MITzbLPvaGLZratTdp/woHuCE6uT8nYyTQDVYwqeTlfj6qjVp1Zp1NaY9LOXhbE1hy/chbLsthQOhzeZl6DOwyYh1MHPT+M0fnKpA//gaxo8otCYuot44LcRRZcI3oY2fxaD/7m8s7+l5/j0CgYEA+bIbXFn4RB/LF1GHkM4oBkNSMvvjMrz73EVWx7RHdsSeDn2LQBIo3foyqTFRdefxdKW2JsAgo0auJR4Oz5/DM9qD8Q4vT2ht5GTY+DmTlx1jbTSb7jVIqKuNr/cnGAXDCTiYO0PZdweLrRJ5ru9VgO/c+e1RIY3q6JPyJ5OqvGcCgYEA2qasapwT5dZVrkglgDk/TBMM5IdrNRo75QZ1De+TPdrWtMA/lA5b4cWqCJxMlgxc8gkxJpRuFuU41D+e0G7/nklUpY0ZaQuwlkvKAH6SoC3SpvxbGQpphUqJRWjdyB8BaFx/PdkCXJtXM8DMOq1ziICArXzadHGqFOkOjRxrUhsCgYA+E4Zz1jY/kXvnJzDB0k7nB7OW00JvqcYfw+lIKsydfVIiHhoRarJYRUx0/brXyjsgGdaIGbnDfd3rgmaCPaDE8m1c737ZigfQATZjt8S2i+rdCng9p2eR71yBQ7unYD9Vuok2Kq8UxX53H6G62Otz664PQG2sHuEowycvqamHvwKBgGW2uWhSuPLnVS5hA4j1mJt0FUBOOrIWRRySd2uHMnDI16537FucnmOVxzaANyRqFebGHeY7kEb4VQpvmhqOOD1TEZx92f9C39/a29qFBwKarm7d4Cby8AmAlgEC+oD443e/57VGuVGJNfSuUJNPUvqCBNovxZP7uEpH7Gv6d3ZXAoGAEZsLA6sw/QpSlwBzOCSbxrB3WzcNSoCgTJ9VVieAf9KFeduEs4y9hydC2bzPKxX/oy/kPi6jaWSgumCTi0yoIE4sHRwgl850scSSmmYfu20uGajSTbPp0yx40czXHDZViULgzzb9oU120SGAtxwd/inuAysQOiXgHWcmQyvCvis=";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toastShort("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toastShort("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        toastShort("授权成功\n" + String.format("authCode:%s"));

                    } else {
                        // 其他状态值则为授权失败
                        toastShort("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    @BindView(R.id.ib_back)
    ImageButton ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.rv_order)
    RecyclerView rvOrder;
    @BindView(R.id.cb_select_all)
    CheckBox cbSelectAll;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.bt_send_order)
    Button btSendOrder;
    @BindView(R.id.tv_no_order)
    TextView tvNoOrder;
    @BindView(R.id.ll_no_order)
    LinearLayout llNoOrder;
    @BindView(R.id.ll_order_content)
    LinearLayout llOrderContent;

    @BindView(R.id.ll_back)
    LinearLayout llBack;


    private Unbinder unbinder;

    private CartAdapter cartAdapter;

    private Order currentOrder = new Order();

    @Override
    public int initLayout() {
        return R.layout.activity_cart;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this, getContentView());

        llOrderContent.setVisibility(View.VISIBLE);
        llNoOrder.setVisibility(View.GONE);

        tvTitle.setText("已挑选商品");
        llBack.setVisibility(View.INVISIBLE);
        tvHome.setVisibility(View.INVISIBLE);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());

        RecyclerView.ItemDecoration decoration = new DividerItemDecoration(getContext(), layoutManager.getOrientation());
        MyApp app = (MyApp) getActivity().getApplication();

        rvOrder.addItemDecoration(decoration);
        rvOrder.setLayoutManager(layoutManager);
        cartAdapter = new CartAdapter(getContext());

        cartAdapter.setOnCartVisibilityChangeListener(this);//设置购物车UI变化的监听（依据有无数据来）

        cartAdapter.setOnPriceChangeListener(this);//设置价格可能变化的监听
        rvOrder.setAdapter(cartAdapter);

    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.cb_select_all, R.id.bt_send_order, R.id.tv_no_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.cb_select_all:
                if (cbSelectAll.isChecked()) {
                    cartAdapter.setSelectedOrderItemList(true);
                } else {
                    cartAdapter.setSelectedOrderItemList(false);
                }
                break;
            case R.id.bt_send_order:
                //creteOrder();
                sendOrder(currentOrder);
                break;
            case R.id.tv_no_order:
                ((MainActivity) getActivity()).selectPage(1);
                break;
        }
    }

    //生成一个订单
//    private void creteOrder() {
//        List<MyOrderItem> selectedOrderItem = cartAdapter.getSelectedItemList();
//        MyApp app = (MyApp) getActivity().getApplication();
//        User user = app.getCurrentUser();
//        if (user == null) {
//            startActivity(new Intent(getContext(), LoginActivity.class));
//            toastShort("请先登陆再执行相关操作");
//            return;
//        }
//        List<Order> orderList = app.getOrderList();
//        List<MyOrderItem> orderItemList = app.getOrderItemList();
//        currentOrder = new Order();//当前订单
//        //MyOrderItem myOrderItem = new MyOrderItem();//用以列表选择的辅助中间变量
//        Long orderNumber = Long.parseLong(CartActivity.getOutTradeNo());
//        currentOrder.setOrderNo(orderNumber);
//        currentOrder.setUserId(user.getId());
//        currentOrder.setCreateTime(new Date());
//
//        float totalPrice = 0;
//        int amount = 0;
//        StringBuilder orderName = new StringBuilder("来自MyShop的支付信息");
//        for (MyOrderItem myOrderItem1 : selectedOrderItem) {
//            OrderItem orderItem1 = myOrderItem1.getOrderItem();
//            orderItem1.setOrderNo(orderNumber);
//            amount = orderItem1.getQuantity();
//            totalPrice = totalPrice + orderItem1.getCurrentUnitPrice().floatValue() * amount;
//            orderItemList.add(myOrderItem1);
//        }
//        if (totalPrice == 0 || amount == 0) {
//            toastShort("订单不合法，请确认");
//            return;
//        }
//
//        currentOrder.setPayment(new BigDecimal(totalPrice));
//
//        orderList.add(currentOrder);
//
//        app.setOrderList(orderList);
//        app.setOrderItemList(orderItemList);
//
//    }

    public static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 10);
        return key;
    }

    /**
     * 发起付款
     *
     * @param order
     */
    private void sendOrder(Order order) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(getContext()).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            //finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        MyApp app = (MyApp) getActivity().getApplication();
        StringBuilder payTitles = new StringBuilder("MyShop:");
        int amount = 0;
//        List<Order> orderList = app.getOrderList();
//        List<MyOrderItem> orderItemList = app.getOrderItemList();
//        for (MyOrderItem myOrderItem : orderItemList) {
//            OrderItem orderItem = myOrderItem.getOrderItem();
//            if (orderItem.getOrderNo() == order.getOrderNo()) {
//                amount += orderItem.getQuantity();
//                payTitles.append(orderItem.getProductName() + ",");
//            }
//        }
        if (amount == 0) {
            toastShort("商品数目非法");
            return;
        }
        Map<String, String> payMap = new HashMap<>();
        payMap.put("subject", payTitles.toString());
        payMap.put("out_trade_no", getOutTradeNo());
        payMap.put("total_amount", amount + "");
        payMap.put("product_code", "QUICK_MSECURITY_PAY");
        Gson gson = new Gson();
        String bizContent = gson.toJson(payMap);

        Log.d(TAG, "onViewClicked: bizContent:" + bizContent);


        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, bizContent);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
        toastShort("提交订单");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void priceChange() {
        tvTotalPrice.setText("￥" + cartAdapter.getTotalPrice() + "");
    }


    @Override
    public void onResume() {
        super.onResume();
        cartAdapter.loadData();
    }

    @Override
    public void onVisibilityChange(boolean visible) {
        if (visible) {
            llOrderContent.setVisibility(View.VISIBLE);
            llNoOrder.setVisibility(View.GONE);
        } else {
            llOrderContent.setVisibility(View.GONE);
            llNoOrder.setVisibility(View.VISIBLE);
        }
    }
}
